<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页</title>
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="assets/css/judgerText.css" rel="stylesheet">
    <link href="./bootstrap-4.6.2/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div id="myModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <p id="modalMessage"></p>
        </div>
    </div>
    <div id="myApp">
        <div id="menuBar">
            <div class="menu-item" id="homeButton" @click="goToHome">首页</div>
            <div class="menu-item" id="scoreHistoryButton" @click="goToScoreHistory">评分记录</div>
        </div>
        <header-component></header-component>
        <carousel-component :images="images" :current-index.sync="currentIndex"></carousel-component>
        <text-module-component></text-module-component>
        <divider-component></divider-component>
        <candidate-list-component :records="records" :judged-candidates="judgedCandidates"
            @open-score-form="openScoreForm"></candidate-list-component>
        <score-form-component v-if="isScoreFormVisible" :score="score" @submit-score="submitScore"
            @close-score-form="closeScoreForm"></score-form-component>
    </div>

    <script src="assets/js/jquery-3.5.1.min.js"></script>
    <script src="./bootstrap-4.6.2/js/bootstrap.bundle.min.js"></script>
    <script src="./vue/vue-2.7.6.min.js"></script>
    <script src="./vue/axios.min.js"></script>
    <script src="./vue/vue-router-3.6.5.js"></script>
    <script src="./assets/js/constants.js"></script>
    <script>
        let ajax = axios.create({
            baseURL: baseURL,
            timeout: 5000
        });

        const user = localStorage.getItem("user");
        const token = user ? JSON.parse(user).token : "";
        ajax.defaults.headers.common['Authorization'] = 'Bearer ' + token;

        Vue.component('header-component', {
            template: `
        <div class="header-container">
            <div class="header">
                <div class="main-title">第484期</div>
                <div class="sub-title">"我与软件有个约会"</div>
            </div>
        </div>
    `
        });

        Vue.component('carousel-component', {
            props: ['images', 'currentIndex'],
            template: `
            <div class="carousel-container">
                <div class="carousel">
                    <img v-for="(image, index) in images" :key="index" :src="image.src" :alt="image.alt" :class="{ active: index === currentIndex }">
                </div>
                <div class="carousel-controls">
                    <button @click="prevImage">❮</button>
                    <button @click="nextImage">❯</button>
                </div>
                <div class="carousel-nav">
                    <button v-for="(image, index) in images" :key="index" @click="goToImage(index)" :class="{ active: index === currentIndex }"></button>
                </div>
            </div>
        `,
            methods: {
                prevImage() {
                    this.$emit('update:currentIndex', this.currentIndex - 1);
                },
                nextImage() {
                    this.$emit('update:currentIndex', this.currentIndex + 1);
                },
                goToImage(index) {
                    this.$emit('update:currentIndex', index);
                }
            }
        });

        Vue.component('text-module-component', {
            template: '<div class="text-module">双体软件精英产业学院</div>'
        });

        Vue.component('divider-component', {
            template: `
            <div class="divider">
                <div class="divider-text">选手风采</div>
            </div>
        `
        });

        Vue.component('candidate-list-component', {
            props: ['records', 'judgedCandidates'],
            template: `
            <div class="candidates-container">
                <div class="candidate" v-for="(candidate, index) in records" :key="index">
                    <img :src="candidate.avatar" alt="Candidate Photo" class="candidate-img">
                    <div class="candidate-name">{{ candidate.matName }}</div>
                    <div class="candidate-department">{{ candidate.plaDepartment }}:</div>
                    <button class="vote-button" @click="openScoreForm(candidate)" :disabled="judgedCandidates.includes(candidate.id)">点击评分</button>
                    <div class="candidate-headline">{{ candidate.matSequence }}号选手<span id="headline"></span></div>
                </div>
            </div>
        `,
            methods: {
                openScoreForm(candidate) {
                    this.$emit('open-score-form', candidate);
                }
            }
        });

        Vue.component('score-form-component', {
            props: ['score'],
            data() {
                return {
                    localScore: this.score,
                    scoreInterval: null
                };
            },
            template: `
        <div>
            <div id="scoreFormOverlay" @click="$emit('close-score-form')"></div>
            <div id="scoreForm">
                <h3>请输入您的评分</h3>
                <div>
                    <div class="decrease-score-div" @mousedown.prevent="startChangeScore(-0.01)" @mouseup="stopChangeScore" @mouseleave="stopChangeScore">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="score-control-button">
                            <path d="M19 13H5v-2h14v2z"/>
                        </svg>
                    </div>
                    <input type="number" id="scoreInput" v-model.number="localScore" step="0.01">
                    <div class="increase-score-div" @mousedown.prevent="startChangeScore(0.01)" @mouseup="stopChangeScore" @mouseleave="stopChangeScore">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="score-control-button">
                            <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
                        </svg>
                    </div>
                </div>
                <div>
                    <button @click="submitScore">提交评分</button>
                    <button @click="$emit('close-score-form')" class="cancel">取消</button>
                </div>
            </div>
        </div>
        `,
            methods: {
                startChangeScore(increment) {
                    this.changeScore(increment);
                    this.scoreInterval = setInterval(() => this.changeScore(increment), 200);
                },
                stopChangeScore() {
                    clearInterval(this.scoreInterval);
                },
                changeScore(increment) {
                    let newScore = this.localScore + increment;
                    if (newScore > 100) newScore = 100;
                    if (newScore < 0) newScore = 0;
                    this.localScore = parseFloat(newScore.toFixed(2));
                },
                submitScore() {
                    let score = parseFloat(this.localScore.toFixed(2));
                    if (score > 100) score = 100;
                    console.log('提交的评分为: ' + score);
                    this.$emit('submit-score', score);
                    this.$emit('close-score-form');
                }
            }
        });

        // 获取模态框元素
        const modal = document.getElementById("myModal");
        const span = document.querySelector(".close");

        // 显示模态框的函数
        function showModal(message) {
            document.getElementById("modalMessage").innerText = message;
            modal.style.display = "block";
        }

        // 关闭模态框的函数
        function closeModal() {
            modal.style.display = "none";
        }

        // 当用户点击关闭按钮时关闭模态框
        span.onclick = closeModal;

        // 当用户点击模态框外部区域时关闭模态框
        window.onclick = event => {
            if (event.target === modal) {
                closeModal();
            }
        };

        const myApp = new Vue({
            el: "#myApp",
            data: {
                records: [],
                images: [
                    { src: "assets/images/71606471114afc3d833160425489b75.jpg", alt: "Image 1" },
                    { src: "assets/images/a63a82977d3af6bd5492dded1c349ad.jpg", alt: "Image 2" },
                    { src: "assets/images/f1f929ada120f085f6524bdb30dc55a.jpg", alt: "Image 3" },
                    { src: "assets/images/4f72514c839168c23ad9b41e59766a4.jpg", alt: "Image 4" },
                    { src: "assets/images/dcdc6c27ee18e406ad1879361078f64.jpg", alt: "Image 5" }
                ],
                currentIndex: 0,
                currentCandidate: null,
                score: 90.00,
                isScoreFormVisible: false,
                judgedCandidates: [],
                ruaNumber: null, // 添加此行
                id: null
            },
            methods: {
                findMyRecords() {
                    ajax.post('/match/players')
                        .then(res => {
                            this.records = res.data.data.map(record => ({
                                ...record,
                                plaId: record.id // 假设plaId实际上是id
                            }));
                        })
                        .catch(error => {
                            console.error('获取记录失败:', error);
                        });
                },
                openScoreForm(candidate) {
                    this.currentCandidate = candidate;
                    this.score = 90.00;
                    this.isScoreFormVisible = true;
                },
                closeScoreForm() {
                    this.isScoreFormVisible = false;
                },
                fetchLastRecord() {
                    ajax.post('/ruanyue/last')
                        .then(response => {
                            console.log('获取记录成功:', response.data);
                            const lastRecord = response.data.data;
                            this.ruaNumber = lastRecord.ruaNumber;
                            this.id = lastRecord.id; // 设置ruaId
                        })
                        .catch(error => {
                            console.error('获取记录失败:', error);
                        });
                },
                submitScore(score) {
                    console.log('提交的评分为: ' + score);

                    const requestData = {
                        plaId: this.currentCandidate.plaId, // 修改此处为plaId
                        recScore: score, // 修改为recScore
                        ruaNumber: this.ruaNumber, // 添加此行
                        ruaId: this.id
                    };

                    ajax.post('/record/score', requestData)
                        .then(response => {
                            console.log('评分提交成功:', response.data);
                            if (response.data.code === 0 && response.data.msg === '评分通道未打开' || response.data.code === 0 && response.data.msg === '当前选手的评分通道尚未开启') {
                                showModal('评分通道尚未打开');
                            } else {
                                showModal('评分提交成功');
                                this.judgedCandidates.push(this.currentCandidate.id);
                                this.closeScoreForm();
                            }
                        })
                        .catch(error => {
                            console.error('评分提交失败:', error);
                            if (error.response && error.response.data) {
                                showModal('评分提交失败: ' + error.response.data.message);
                            } else {
                                showModal('评分提交失败，请稍后再试');
                            }
                        });
                },
                goToHome() {
                    window.location.href = 'judgerTex.html';
                },
                goToScoreHistory() {
                    window.location.href = 'PFcode.html';
                }
            },
            created() {
                this.fetchLastRecord(); // 调用获取最后一条记录的方法
                this.findMyRecords();
                setInterval(() => {
                    this.currentIndex = (this.currentIndex + 1) % this.images.length;
                }, 3000);
            }
        });
    </script>
</body>

</html>